<?php
/**
 * 配置管理
 * @author Mortimer He <mortimerhe@163.com>
 */
namespace Manage\Controller;
use Common\Library\Page;
class ConfigController extends CommonController{
	private $msg=array();
	private $module=array();
	private $type=array();
	private $Model;
	private $GroupModel;
	function _initialize(){
		parent::_initialize();
		//配置模型
		$this->Model=M('Config');
		//配置分组模型
		$this->GroupModel=M('ConfigGroup');
		//配置类型
		$this->type=array(1=>L('type_input'),2=>L('type_integer'),3=>L('type_boolean'),4=>L('type_enumerate'),5=>L('type_image'));
		//配置的作用范围
		$this->module=array('Home'=>L('text_module_home'),'Manage'=>L('text_module_manage'),'Common'=>L('text_module_common'));

	}
	/**
	 * 列表
	 */
	public function index(){
		if(!$this->checkPermission('Config')) $this->jump();
		//分组为0或配置类型为0为系统必须配置，不能被修改或者删除
		$map=array(
			'config_group'	=> 	array('gt',0),
			'type'			=>	array('gt',0)
			);
		$count = $this->Model->where($map)->count();
		$url['p']=I('get.p','');
		$Page = new Page($count,C('CONFIG_LIMIT_MANAGE'));
		$Page->setConfig('header',L('page_header'));
		$Page->setConfig('theme',L('page_theme'));
		$show=$Page->show();
		$list=$this->Model->where($map)->order('sort_order asc')->limit($Page->firstRow,$Page->listRows)->select();
		$language_id=get_default_lng_id();
		foreach ($list as $k => $v) {
			$group=$this->GroupModel->where(array('config_group_id'=>$v['config_group_id']))->find();
			if(isset($group['text'])){
				$group_text=json_decode($group['text'],true);
				$group_text=$group_text[$language_id];
			}else{
				$group_text=array();
			}
			$list[$k]['group_title']=isset($group_text['title'])?$group_text['title']:'';
			$text=json_decode($v['text'],true);
			$list[$k]['title']	= isset($text[$language_id]['title'])?	$text[$language_id]['title'] : '';
		}
		$this->assign('modules',$this->module);
		$this->assign('list',$list);
		$this->assign('url',$url);
		$this->assign('type',$this->type);
		$this->assign('page',$show);
		$this->display();
	}
	/**
	 * 新增/修改
	 */
	public function oper($config_id=0){
		if(!$config_id && !$this->checkPermission('ConfigAdd')) $this->jump();
		$config=array();
		if($config_id){
			$map=array(
				'config_id'	=> $config_id,
				'config_group_id' => array('gt',0),
				'type'	=>	array('gt',0)
				);
			$config=$this->Model->where($map)->find();
			if(empty($config)) $this->jump(L('error_404'));
			$config['text']=json_decode($config['text'],true);
			$config['extra']=json_decode($config['extra'],true);
			$config['remark']=json_decode($config['remark'],true);
		}
		if(IS_POST){
			$config=I('post.');
			if($this->validateForm()){
				$config['text']=json_encode($config['text']);
				$config['extra']=json_encode($config['extra']);
				$config['remark']=json_encode($config['remark']);
				$group=$this->GroupModel->where(array('config_group_id'=>$config['config_group_id']))->find();
				$config['module']=$group['module'];
				if($config_id){
					$config['date_modified']=time();
					$this->Model->where(array('config_id'=>$config_id))->save($config);
					$jump_tip=L('success_edit');
				}else{
					$config['date_added']=time();
					$config['date_modified']=time();
					$this->Model->add($config);
					$jump_tip=L('success_add');
				}
				$url['p']=I('get.p','');
				session('success',$jump_tip);
				$this->redirect('index',$url);
			}else{
				if(!isset($this->msg['warning'])) $this->msg['warning']=L('error_warning');
			}
		}
		$language_id=get_default_lng_id();
		$config_group=$this->GroupModel->order('sort_order asc')->select();
		foreach ($config_group as $key => $value) {
			$text=json_decode($value['text'],true);
			$config_group[$key]['text']=$text;
			$config_group[$key]['title']=$text[$language_id]['title'];
		}
		$this->assign('config',$config);
		$this->assign('config_group',$config_group);
		$this->assign('languages',get_langs());
		$this->assign('msg',$this->msg);
		$this->assign('type',$this->type);
		$this->display();

	}
	/**
	 * 验证
	 */
	private function validateForm(){
		$config_id=I('get.config_id',0);
		if($config_id && !$this->checkPermission('ConfigEdit')){
			$this->msg['warning']=L('error_not_permission');
		}else{
			$data=I('post.');
			foreach($data['text'] as $language_id => $text){
				if(mb_strlen($text['title'])<2 || mb_strlen($text['title'])>50) $this->msg['title'][$language_id]=L('error_title');
			}
			foreach($data['remark'] as $language_id => $remark){
				if(mb_strlen($remark['description'])>200) $this->msg['description'][$language_id]=L('error_description');
			}
			if(mb_strlen($data['key'])>50 || mb_strlen($data['key'])<2) {
				$this->msg['key']=L('error_key');
			}else{
				$group=$this->GroupModel->where(array('config_group_id'=>$data['config_group_id']))->find();
				$module=$group['module'];
				$map=array(
					'config_group_id' => array('in',array($data['config_group_id'],0)),
					'module'=>	$group['module'],
					'_logic'=>'OR'
					);
				$where=array(
					'_complex' => $map,
					'config_id'=>array('neq',$config_id),
					'key'	=>	$data['key'],			
					);
				$check=$this->Model->where($where)->find();
				if(!empty($check)) $this->msg['key']=L('error_key_exist');
			}
		}
		return !$this->msg;
	}
	/**
	 * 系统配置
	 * 只能修改配置的值，而配置项不需要修改的配置
	 */
	public function config(){
		if(!$this->checkPermission('Config')) $this->jump();
		$config=array(
			//前面默认模板
			'Home'	=>	array(
				'DEFAULT_LANG'			=>	get_config_by_key('DEFAULT_LANG','Home'),
				'DEFAULT_THEME'			=>	get_config_by_key('DEFAULT_THEME','Home')
				),
			'Manage'=>	array(
				'DEFAULT_THEME'			=>	C('DEFAULT_THEME'),
				'DEFAULT_LANG'			=>	C('DEFAULT_LANG'),
				'CONFIG_LIMIT_MANAGE'	=>	C('CONFIG_LIMIT_MANAGE')
				)				
			);			
		if(IS_POST){
			$config=I('post.');
			if($this->validateConfigForm()){
				foreach($config['Home'] as $k=>$v){
					$map=array('key'=>$k,'module'=>'Home');
					$this->Model->where($map)->setField('value',$v);
				}
				foreach($config['Manage'] as $k=>$v){
					$map=array('key'=>$k,'module'=>'Manage');
					$this->Model->where($map)->setField('value',$v);
				}
				//配置修改后更新配置缓存
				S('DB_CONFIG_DATA',null);
				S('DB_CONFIG_DATA_MANAGE',null);
				session('success',L('success_edit'));
				$this->redirect('config');
			}else{
				if(!isset($this->msg['warning'])) $this->msg['warning']=L('error_warning');
			}
		}
		//前端模板列表
		$home_theme=array_diff( scandir(APP_PATH . 'Home/View/'), Array( ".", ".." ) );
		//后台模板列表
		$manage_theme= array_diff(scandir(APP_PATH . 'Manage/View/'), Array( ".", ".." ) );
		$this->assign('config',$config);
		$this->assign('home_theme',$home_theme);
		$this->assign('manage_theme',$manage_theme);
		$this->assign('languages',get_langs());
		$this->display();
	}

	/**
	 * 常规配置
	 * 配置值和配置项都可以被修改的配置内容
	 * 通常用在开发者一发个新的功能须要用到配置时，在这里添加配置，而无须修改配置文件
	 */
	public function general(){
		$config['Home']=$this->getConfig('Home');
		$config['Manage']=$this->getConfig('Manage');
		$config['Common']=$this->getConfig('Common');
		if(IS_POST){
			if($this->validateGeneral()){
				$cfg=I('post.');
				foreach($cfg['Home'] as $k=>$v){
					$map=array('key'=>$k,'module'=>'Home');
					$this->Model->where($map)->setField('value',$v);
				}
				foreach($cfg['Manage'] as $k=>$v){
					$map=array('key'=>$k,'module'=>'Manage');
					$this->Model->where($map)->setField('value',$v);
				}
				foreach($cfg['Common'] as $k=>$v){
					$map=array('key'=>$k,'module'=>'Common');
					$this->Model->where($map)->setField('value',$v);
				}
				//配置修改后更新配置缓存
				S('DB_CONFIG_DATA',null);
				S('DB_CONFIG_DATA_MANAGE',null);
				session('success',L('success_edit'));
				
			}else{
				session('danger',$this->msg['warning']);
			}
			$this->redirect('general');
		}
		$placeholder=image_resize();
		$this->assign('config',$config);
		$this->assign('placeholder',$placeholder);
		$this->display();
	}
	/**
	 * 获取某分组下的配置项
	 */
	private function getConfig($module='Home'){
			$groups=$this->GroupModel->where(array('module'=>$module))->order('sort_order')->select();
			$config_group=array();
			$language_id=get_default_lng_id();
			foreach ($groups as $k => $v) {
				$confs=$this->Model->where(array('config_group_id'=>$v['config_group_id']))->order('sort_order asc')->select();
				$configs=array();
				foreach ($confs as $key => $value) {
					$text=json_decode($value['text'],true);
					$remark=json_decode($value['remark'],true);
					$extras=json_decode($value['extra'],true);
					$extra=array();
					foreach ($extras as $ek => $ev) {
						$extra[]=array(
							'title'	=>	isset($ev['text'][$language_id]['title'])?$ev['text'][$language_id]['title']:'',
							'value'	=>	$ev['value']
							);
					}
					if($value['type']==5){
						$thumb=image_resize($value['value'],100,100);
					}else{
						$thumb='';
					}
					$configs[]=array(
						'config_id'=>$value['config_id'],
						'key'	=>	$value['key'],
						'title'	=>	$text[$language_id]['title'],
						'extra'	=>	$extra,
						'remark'=>	isset($remark[$language_id]['description'])?$remark[$language_id]['description']:'',
						'module'=>	$value['module'],
						'config_group_id'=>$value['config_group_id'],
						'type'	=>	$value['type'],
						'value'	=>	$value['value'],
						'thumb'	=>	$thumb
						);
				}
				$text=json_decode($v['text'],true);
				$config_group[]=array(
					'title'		=>	$text[$language_id]['title'],
					'config_group_id'=>$v['config_group_id'],
					'module'	=>	$v['module'],
					'config'	=>	$configs
					);
			}
		return $config_group;	
	}
	/**
	 * 常规配置表单验证
	 */
	private function validateGeneral(){
		if(!$this->checkPermission('ConfigGeneral')) $this->msg['warning']=L('error_not_permission');
		return !$this->msg;
	}
	/**
	 * 系统配置表单验证
	 */
	private function validateConfigForm(){
		if(!$this->checkPermission('EditConfig')){
			$this->msg['warning']=L('error_not_permission');
			return !$this->msg;
		}
		$data=I('post.');
		if(!is_numeric($data['Manage']['CONFIG_LIMIT_MANAGE']) || $data['Manage']['CONFIG_LIMIT_MANAGE']>100 || $data['Manage']['CONFIG_LIMIT_MANAGE']<0){
			$this->msg['manage_page_limit']=L('error_manage_page_limit');
		}
		return !$this->msg;
	}

	/**
	 * 删除配置项
	 */
	public function del(){
		if($this->checkPermission('ConfigDelete')){
			$ids=I('post.selected');
			$count=0;
			if(!empty($ids)){
			$map=array(
				'config_id'	=>	array('in',$ids),
				'config_group_id'=>	array('gt',0)
				);
				$count=$this->Model->where($map)->delete();
			}
			if($count){
				session('success',L('success_delete',array('count'=>$count)));
			}else{
				session('danger',L('error_not_selected'));
			}
		}else{
			session('danger',L('error_not_permission'));
		}
		$url['p']=I('get.p');
		$this->redirect('index',$url);
	}
}